#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<linux/stat.h>
#include<signal.h>

#define PUBLIC_FIFO "PUBFIFO"
#define PRIVATE1_FIFO "PRIFIFO1"
#define PRIVATE1_HEADER "Client1's message:"

int main(int argc,char *argv[])
{
	int fd;
	int fd1;
	pid_t pid;
	char num[100]="";
    char buf[200]="";
	char str[100]=PRIVATE1_HEADER;

	if((fd1=open(PRIVATE1_FIFO,O_RDONLY)) == -1)
	{
		printf("Open fail.\n");
		exit(1);
	}
	if(read(fd1,buf,200)!=-1)
	{
		printf("%s\n",buf);
		close(fd1);
	}
	usleep(200000);

	pid = fork();
	if(pid<0)
	{
		printf("error");
	}
	else if(pid == 0)	// 子进程读数据
	{
		while(1)
		{
			memset(buf, 0, 200);
			if((fd1=open(PRIVATE1_FIFO,O_RDONLY)) == -1)
			{
				printf("Open fail.\n");
				exit(1);
			}
			if(read(fd1,buf,200)!=-1)
			{
				printf("%s\n",buf);
				close(fd1);
			}
			usleep(200000);
		}
		
	}
	else	// 父进程写数据
	{
		while(1)
		{
			if((fd=open(PUBLIC_FIFO,O_WRONLY)) == -1)
			{
				printf("Open failed.\n");
				exit(1);
			}
			memset(num,0,100);
			fgets(num,100,stdin);
			if(strncmp(num,"end",3) == 0)
			{
				kill(pid, SIGSTOP);			// 结束子进程
				unlink(PRIVATE1_FIFO);		// 删除管道文件
                usleep(200000);
				printf("Bye!\n");
                exit(0);
			}
			strcpy(str,PRIVATE1_HEADER);
			strcat(str,num);
			// printf("write str: %s\n", str);
			if(write(fd,str,strlen(str))>0)
			{
				close(fd);
			}
			usleep(200000);
		}
		
	}
	
	return 0;

}

